package com.songcha.library_base.mvvm.base


import com.songcha.library_base.mvvm.exception.NoNetworkException
import com.songcha.library_common.LibraryCommon
import com.songcha.library_network.util.NetworkUtil
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import java.lang.Exception


abstract class BaseRepository() {

    protected fun <T> createObservable(block:(obs:ObservableEmitter<T>)->Unit):Observable<T>{
        val observable=Observable.create<T>{
                try{
                    block(it)
                }catch (e:Exception){
                    it.onError(e)
                }
        }
        return observable
    }

    protected fun <T> createNetworkObservable(block:(obs:ObservableEmitter<T>)->Unit):Observable<T>{
        val observable=Observable.create<T>{
            if(!NetworkUtil.isNetworkAvailable(LibraryCommon.getContext())){
                it.onError(NoNetworkException())
            }else{
                try{
                   block(it)
                }catch (e:Exception){
                    it.onError(e)
                }

            }
        }
        return observable
    }


  /*  fun json2Map(json: JSONObject): MutableMap<String, Any> {
        val m: MutableMap<String, Any> = mutableMapOf()
        return GsonBuilder().registerTypeAdapter(m.javaClass, GsonMapAdapter()).create()
            .fromJson(json.toString(), m.javaClass)
    }*/



    /*suspend fun <T: BaseBean> sendRequest(json:JSONObject = JSONObject(), block: IApiCallback<T>){
        if(!NetworkUtil.isNetworkAvailable(MyApplication.getContext())){
            block.onNoNetwork()
        }

        val result=withContext(this.dispatcher) {
            try {
                val bean = sendRequest_(json) as T
                return@withContext ApiResult.Success(bean)
                //return@withContext ApiResult.Success(bean)
            } catch (e: Exception) {
                e.printStackTrace()
                //ToastUtil.show(bean.msg)
                return@withContext ApiResult.Error(e)
                //Log.e("api exception",e.message)
            }
            //return@withContext request_(body)
        }

        if(result is ApiResult.Success){
            block.onSuccess(result.data)
        }else if(result is ApiResult.Error){
            ExceptionHandler.handle(result.exception)
            block.onError(result.exception)
        }


    }*/



      //abstract protected suspend fun sendRequest_(json:JSONObject?): BaseBean



    //withcontext


}